<template>
  <div class="manage">
    <div class="manage-header">
      <!-- 新增按钮 -->
      <el-button type="primary" @click="handlecreate">+ 新增用户</el-button>
      <!-- 对话框:点击新增或编辑才会弹出表单 -->
      <!-- :before-close="closeDialog" 点击关闭的x之前要做的事情 -->
      <el-dialog :title="modalType === 0 ? '新建' : '编辑'" :visible.sync="dialogVisible" width="500px" :before-close="closeDialog">
        <!-- 表单Form -->
        <!-- ref=form:为了通过this.$refs调用组件的方法 -->
        <el-form :inline="false" :model="form" :rules="rules" ref="form" label-width="80px">
          <!-- 每一项表单域:el-form-item -->

          <el-form-item label="用户名" prop="userName">
            <el-input placeholder="请输入用户名" v-model="form.userName"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input type="password" placeholder="请输入密码" v-model="form.password" show-password></el-input>
          </el-form-item>

          <el-form-item label="权限" prop="userPermission">
            <el-select style="width: 100%" v-model="form.userPermission" placeholder="请选择权限">
              <el-option label="普通用户" :value="0"></el-option>
              <el-option label="管理员" :value="1"></el-option>
              <el-option label="超级管理员" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 搜索框 -->
      <!-- <el-form :inline="true">
        <el-form-item>
          <el-input v-model="searchForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form> -->
    </div>
    <div class="common-table">
      <!-- 用户数据Table -->
      <el-table :data="tableData" stripe style="width: 100%" height="90%">
        <el-table-column prop="userName" label="用户名"></el-table-column>
        <el-table-column prop="userPermission" label="权限">
          <template slot-scope="scope">
            <span>{{ permissionType[scope.row.userPermission] }}</span>
          </template>
        </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button class="danger-text" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pager">
        <el-pagination layout="prev, pager, next" :total="total" @current-change="currentChange"> </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { addUserApi, getAllUserInfoApi, editUserApi, deleteUserApi } from "@/api/userApi";

export default {
  data() {
    return {
      // 表单绑定的数据
      permissionType: {
        0: "普通用户",
        1: "管理员",
        2: "超级管理员",
      },
      form: {
        userId: "",
        password: "",
        userName: "",
        userPermission: "",
      },
      // 表单验证规则
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        userPermission: [{ required: true, message: "请选择权限", trigger: "blur" }],
      },
      // 表单是否打开
      dialogVisible: false,
      // 列表数据
      tableData: [],
      // 打开表单:新建0,编辑1
      modalType: 0,
      // 分页的对象
      pageData: {
        page: 1,
        limit: 20,
      },
      // 分页页数
      total: 0,
      // 搜索框表单
      searchForm: {
        userName: "",
      },
    };
  },

  mounted() {
    this.handleAllUserInfoList();
  },
  methods: {
    // 获取用户列表
    async handleAllUserInfoList() {
      const list = await getAllUserInfoApi();
      console.log(list, "用户信息");
      if (list && list.length) {
        this.tableData = list;
        this.total = list.length;
      } else {
        this.tableData = [];
        this.total = 0;
      }
    },

    // 表单提交
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          console.log(this.form);
          if (this.modalType === 0) {
            const res = await addUserApi({
              params: {
                userId: this.form.userId,
                userPermission: this.form.userPermission,
                userName: this.form.userName,
                password: this.form.password,
              },
              traceId: new Date().getTime().toString(),
            });
            if (!res) {
              this.$message.error("添加失败，请重试！");
            } else {
              this.$message.success("添加成功！");
              this.handleAllUserInfoList();
            }
          } else {
            const res = await editUserApi({
              params: {
                userId: this.form.userId,
                userPermission: this.form.userPermission,
                userName: this.form.userName,
                password: this.form.password,
              },
              traceId: new Date().getTime().toString(),
            });
            if (!res) {
              this.$message.error("编辑失败，请重试！");
            } else {
              this.$message.success("编辑成功！");
              this.handleAllUserInfoList();
            }
          }
          this.closeDialog();
        }
      });
    },
    // 关闭对话框
    closeDialog() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    // 编辑按钮
    handleEdit(row) {
      this.modalType = 1;
      this.openForm();
      this.form = JSON.parse(JSON.stringify(row));
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteUserApi({
            params: [row.userId],
            traceId: new Date().getTime().toString(),
          });
          if (!res) {
            this.$message({
              type: "info",
              message: "删除失败，请重试",
            });
          } else {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
          this.handleAllUserInfoList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "删除失败，请重试",
          });
          this.handleAllUserInfoList();
        });
    },
    // 新建按钮
    handlecreate() {
      this.modalType = 0;
      this.openForm();
    },
    // 打开表单
    openForm() {
      this.dialogVisible = true;
    },
    // 改变页码
    currentChange(val) {
      this.pageData.page = val;
      this.handleAllUserInfoList();
    },
    // 搜索
    search() {
      this.handleAllUserInfoList();
    },
  },
};
</script>

<style lang="less" scoped>
.manage {
  height: 100%;

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    margin-top: 20px;
    height: calc(100% - 60px);
    position: relative;

    .pager {
      position: absolute;
      right: 20px;
      bottom: 0;
    }
  }
}

/deep/.el-dialog__body {
  padding: 15px 20px;
}
/deep/ .el-dialog__footer {
  padding-top: 0px;
}
</style>
